package com.bt.lms.ui.action.registration.stu;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.RegStuBizTypeConstant;
import com.bt.lms.entity.RegStuInfo;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.page.stu.PageAddStuInfo;
import com.bt.lms.ui.page.stu.vo.RegistrationStuVo;

import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.FileChooser;


import java.awt.*;
import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 新增报名信息上传身份证事件
 */
public class PageAddApplyStuSelectIDFileBtnAction implements EventHandler {


    @Override
    public void handle(Event event) {


        //文件选择器
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择身份证文件");
        File filePath = fileChooser.showOpenDialog(null); //返回的就是文件路径

        String fileName = null;
        try {
            fileName = filePath.getName();
        } catch (Exception e) {
            return;
        }
        //如果文件不是以.jpg .jpeg .gif .pdf .png     endsWith   以...后缀结尾
        if (!fileName.endsWith(".jpg") && !fileName.endsWith(".jpeg") && !fileName.endsWith(".gif") && !fileName.endsWith(".pdf") && !fileName.endsWith(".png")) {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText("文件格式有误，仅支持 jpg、jpeg、gif、pdf、png");//弹出内容
            alert.showAndWait();
            return;
        }
        int length = fileName.length();
        Integer size = 50;
        if (length > size) {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText("文件不能超过50MB");
            alert.showAndWait();

        }

        try {
            //文件读取流
            FileInputStream fileIn = new FileInputStream(filePath);

            byte[] buffer = new byte[1024];
            //读
            fileIn.read(buffer);

            //文件url集合
            List<String> fileUrls = new ArrayList<>();
            fileUrls.add(filePath.toString());

            //带走
            RegistrationStuVo registrationStuVo = new RegistrationStuVo();
            registrationStuVo.setUrl(fileUrls);


            //组包
            byte[] bytes = getBytes(filePath);

            //获取网络
            Socket socket = getSocket();


            //发送消息
            boolean sendReqMsg = sendReqMsg(socket, bytes, filePath);


        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    /**
     * 发送消息
     *
     * @param socket   网络
     * @param bytes    bytes
     * @param filePath
     * @return 是否成功
     */
    private boolean sendReqMsg(Socket socket, byte[] bytes, File filePath) {

        //输出流
        try {
            OutputStream out = socket.getOutputStream();
            out.write(bytes);
            out.flush();


            //接收响应消息
            RespMsg acceptReqMsg = acceptReqMsg(socket, filePath);


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return true;
    }

    /**
     * 接收响应消息
     *
     * @param socket   网
     * @param filePath 文件路径
     * @return 响应消息
     */
    private RespMsg acceptReqMsg(Socket socket, File filePath) {


        RespMsg respMsg = null;
        //读取流
        try {
            InputStream in = socket.getInputStream();
            byte[] buffer = new byte[1024];

            in.read(buffer);

            //响应消息

            respMsg = RespMsg.toRespMsg(buffer);
            String data = respMsg.getData();
            if (data != null) {

                //如果数据不为空弹出窗口
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("身份证上传");
                alert.setContentText("身份证上传成功，请查看");
                alert.show();

                //文件分隔符
                String url = "file:" + File.separator + filePath.toString();

                File file = new File(url);
                //图片回显
                Image image = new Image(file.toString());
                ImageView imageView = new ImageView(image);
                imageView.setFitHeight(300);
                imageView.setFitWidth(300);
                ObservableList<Node> children = PageAddStuInfo.idhBox.getChildren();
                if (children.size() == 2) {
                    children.add(1, imageView);

                } else if (children.size() == 3) {
                    children.set(1, imageView);
                }
            }
            //关流
            in.close();
            socket.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return respMsg;
    }

    /**
     * 组网
     *
     * @return
     */
    private Socket getSocket() {

        String ip = "127.0.0.1";
        Integer port = 8888;
        Socket socket = null;
        try {
            socket = new Socket(ip, port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return socket;
    }

    /**
     * 文件转为byte
     *
     * @param filePath 文件路径
     * @return byte数组
     */
    private byte[] getBytes(File filePath) {

        //请求消息

        ReqMsg reqMsg = new ReqMsg();
        RegStuInfo regStuInfo = new RegStuInfo();

        regStuInfo.setIdCardUrl(filePath.toString());

        //业务类型
        reqMsg.setBizType(RegStuBizTypeConstant.STU_REG_INFO_ADD);


        String filePathStr = JSON.toJSONString(regStuInfo);


        //带走
        reqMsg.setData(filePathStr);

        byte[] bytes = reqMsg.toBytes();


        return bytes;
    }

//    /**
//     * 文件转为byte
//     *
//     * @param filePath 文件路径
//     * @return byte数组
//     */
//    private byte[] getBytes(String filePath) {
//
//
//        byte[] buffer = new byte[0];
//
//        FileInputStream fileInputStream = null;
//        ByteArrayOutputStream byteArrayOutputStream = null;
//
//        File file = new File(filePath);
//        try {
//            //文件流读取
//            fileInputStream = new FileInputStream(file);
//            byteArrayOutputStream = new ByteArrayOutputStream(1024);//存储缓冲区
//            //准备缓冲区1024字节
//            byte[] buf = new byte[1024];
//            int bytesRead;
//            while ((bytesRead = fileInputStream.read(buf)) != -1) {
//                byteArrayOutputStream.write(buf, 0, bytesRead);//写入指定的数组
//
//            }
//            buffer = byteArrayOutputStream.toByteArray();//新分配的数组
//
//        } catch (FileNotFoundException e) {
//            throw new RuntimeException(e);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        return buffer;
//    }

}
